<?php
/**
 * GeoContexter
 * @link http://code.google.com/p/geocontexter/
 * @package GeoContexter
 */

/**
 * search for list items
 *
   USAGE:
   <pre>

   $ItemSearch = $this->CoreModel('ItemSearch');

   $params  = array('search'          => string,
                    // limit search to id_list(s) and all its descendend id_lists
                    'in_id_list'      => bigint as string or many bigint as string in array,
                    // get default custom attributes: true = get them, false = get non default
                    'default_display' => bool,
                   // 'system_serial' field is included in the result
                   // it contains the system serial if id_group is within the system serial
                   // else null
                   'system_serial' => bool); // optional , value: true

   $this->view->result = $ItemSearch->run( $params );

   $totalNumRows = $ItemSearch->totalNumRows();


   </pre>
 * @package GeoContexter
 * @subpackage Module_Geocontexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev: 828 $ / $LastChangedDate: 2011-02-27 10:30:28 +0100 (So, 27 Feb 2011) $ / $LastChangedBy: armand.turpel $
 */

namespace Youobserve\Model;

use Core\Model\AbstractModel;
use Core\Model\InterfaceModel;

class ItemSearch extends    AbstractModel
                 implements InterfaceModel
{
    /**
     * @param array $params
     */
    public function run( $params )
    {
        try {

            $this->validate_params($params);

            $_sql_limit = '';
            if (isset($params['limit'])) {
                $_sql_limit = 'LIMIT ' . $params['limit'][0] . ' OFFSET ' . $params['limit'][1];
            }

            $sql = 'SELECT id_item AS id, title AS value, title AS label
                    FROM  geocontexter.gc_item
                    WHERE title ILIKE ?
                    ORDER BY title ' . $_sql_limit;

            return $this->query($sql, array($this->search . '%'));

        } catch(\Exception $e) {
            throw $e;
        }
    }

    /**
     * set and validate parameters
     *
     *
     * @param array $params
     */
    private function validate_params( & $params )
    {
        if (!isset($params['search'])) {
            throw new \Exception('search field isnt defined');
        } else {
            $this->search = $params['search'];
        }


    }
}